package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.example.bean.Discount;
import org.example.config.JwtConfig;
import org.example.handler.UserNotFoundException;
import org.example.mapper.DiscountMapperrr;
import org.example.service.DiscountService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:Liu
 * @Testname:DiscountServiceImpl
 * @Date:2025/8/19 9:54
 */
@Service
public class DiscountServiceImpl extends ServiceImpl<DiscountMapperrr, Discount> implements DiscountService {
    /**
     * 添加与更新数据
     *
     * @param discount
     * @return
     */
    @CacheEvict(cacheNames = "BookList", allEntries = true)
    public JsonResult SaveOrUpdate(Discount discount, String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        discount.setUserId(userId);
        boolean b = saveOrUpdate(discount);
        if (!b) {
            throw new UserNotFoundException("添加或修改失败!");
        } else {
            return ResultTool.success("success");
        }
    }

    /**
     * 设置折扣率
     *
     * @param bookId
     * @return
     */
    @Override
    public JsonResult findDiscountPriceByBookId(String bookId) {
        QueryWrapper<Discount> wrapper = new QueryWrapper<>();
        wrapper.eq("book_id", bookId);
        wrapper.eq("status", 1);
        Discount one = getOne(wrapper);
        if (one == null) {
            return ResultTool.fail(209, "这本图书没有折扣");
        }
        return ResultTool.success(one);
    }
}
